package com.pocketsweet.ui.fragments;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.lidroid.xutils.ViewUtils;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.model.MLArticle;
import com.pocketsweet.model.MLArticleLike;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Profile;
import com.pocketsweet.ui.TopicArticle;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.adapter.LikeRecommendAdapter;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

public class LikeRecommendFragment extends Fragment implements
        OnRefreshListener, OnLoadListener, OnItemClickListener {

    private AutoListView likeRecommendListview = null;
    private LikeRecommendAdapter likeRecommendAdapter;
    private List<MLArticle> articleList = new ArrayList<MLArticle>();
    private List<MLArticle> articleLikeList = new ArrayList<MLArticle>();
    private MLApplication mlApplication;
    private LinearLayout linBlank;
    private TextView tvBlankNoLove;
    private TextView tvBlankNoLover;
    private TextView tvBlankBg;
    private LoadingDailog mLoadingDialog;
    public static final int BEGIN_TO_LOADING = -1;
    private int skipDataCount = 0; // 忽略前N个对象
    public static final int MORE_DATA_MAX_COUNT = 20; // 每页10个对象
    private boolean isUpdateList = false; // 是否刷新列表

    // private BroadcastReceiver receiver = new BroadcastReceiver() {
    // @Override
    // public void onReceive(Context context, Intent intent) {
    // if (intent.getAction().equals(Main.ACTION_LIKE_RECOMMEND)) {
    // getUserLikerList();
    // likeRecommendAdapter.notifyDataSetChanged();
    // }
    // }
    // };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater
                .inflate(R.layout.fragment_like_recommend, null);
        mlApplication = (MLApplication) getActivity().getApplication()
                .getApplicationContext();
        ViewUtils.inject(this, rootView);
        // initListview();
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        mLoadingDialog = ToolKits.createLoadingDialog(getActivity(), "登陆中...");
        mLoadingDialog.setText("加载中");
        getUserLikerList(AutoListView.REFRESH);
    }

    private void initView() {
        // TODO Auto-generated method stub
        likeRecommendListview = (AutoListView) getView().findViewById(
                R.id.id_stickynavlayout_innerscrollview);
        linBlank = (LinearLayout) getView().findViewById(
                R.id.linBlankNoRecommend);
        tvBlankBg = (TextView) getView().findViewById(R.id.tvBlankBg);
        tvBlankNoLove = (TextView) getView().findViewById(R.id.tvBlankNoLove);
        tvBlankNoLover = (TextView) getView().findViewById(R.id.tvBlankNoLover);
        likeRecommendAdapter = new LikeRecommendAdapter(getActivity(),
                articleList);
        likeRecommendListview.setAdapter(likeRecommendAdapter);
        likeRecommendAdapter.notifyDataSetChanged();
        likeRecommendListview.setPageSize(MORE_DATA_MAX_COUNT);
        // likeRecommendListview.setOnRefreshListener(this);
        likeRecommendListview.setOnLoadListener(this);
        likeRecommendListview.setOnItemClickListener(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        // IntentFilter filter = new IntentFilter();
        // filter.addAction(Main.ACTION_LIKE_RECOMMEND);
        // registerReceiver(receiver, filter);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    //
    // @Override
    // public void onDestroy() {
    // super.onDestroy();
    // // unregisterReceiver(receiver);
    // }

    /*
     * 请求最近在线对象
     */
    private void getUserLikerList(final int what) {
        // mLoadingDialog.show();
        linBlank.setVisibility(View.GONE);
        if (MLContext.getUserLikeSize("articleSize") != -1) { // 当sharepreference有点赞纪录时从本地获取
            ArrayList<String> tempArray = new ArrayList<String>();
            ArrayList<String> articleArray = new ArrayList<String>();
            tempArray = MLContext.getLike(MLContext.LIKE_TYPE_RECOMMEND);
            for (String articleId : tempArray) {
                if (!StringUtils.isEmpty(articleId)) {
                    articleArray.add(articleId);
                    // Log.e("===articleId==", "articlePreferences:" +
                    // articleId);
                }
            }
            Collections.reverse(articleArray);

            if (articleArray.size() <= 0) {
                likeRecommendListview.setNoData();
                if (what != AutoListView.LOAD) {
                    tvBlankBg.setBackgroundResource(R.drawable.blank_no_like);
                    tvBlankNoLove.setText(getResources().getString(
                            R.string.blank_no_like));
                    tvBlankNoLover.setText(getResources().getString(
                            R.string.blank_no_like_else));
                    linBlank.setVisibility(View.VISIBLE);
                    tvBlankNoLover.setVisibility(View.VISIBLE);
                    tvBlankNoLove.setVisibility(View.VISIBLE);
                    return;
                }
            }
            if (what != BEGIN_TO_LOADING) {
                isUpdateList = true; // 如果不是首次加载数据，则该动作为刷新
            } else {
                likeRecommendListview.setRefreshData(); // 初始化显示loading动态图片
            }
            if (articleLikeList == null || articleLikeList.size() <= 0
                    || isUpdateList) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud

                final AVQuery<MLArticleLike> query = new AVQuery<MLArticleLike>(
                        "MLArticleLike");
                skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
                if (what != AutoListView.LOAD) {
                    skipDataCount = 0; // 刷新时不用忽略前面对象
                }
                MLUser mlUser = new MLUser();
                mlUser.setObjectId(UserService.getCurrentUserId());
                query.whereEqualTo("user", mlUser);
                query.include("article");
                query.setSkip(skipDataCount); // 忽略前N个
                query.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
                query.orderByDescending("createdAt");
                query.findInBackground(new FindCallback<MLArticleLike>() {

                    @Override
                    public void done(List<MLArticleLike> mlArticleLike,
                                     AVException arg1) {
                        // mLoadingDialog.dismiss();
                        if (arg1 == null) {
                            // Log.e("===articleId==",
                            // "articlePreferences:"
                            // + String.valueOf(articleList.size()));
                            if (mlArticleLike.size() <= 0) {
                                if (what != AutoListView.LOAD) {
                                    tvBlankBg
                                            .setBackgroundResource(R.drawable.blank_no_like);
                                    tvBlankNoLove.setText(getResources()
                                            .getString(R.string.blank_no_like));
                                    tvBlankNoLover
                                            .setText(getResources()
                                                    .getString(
                                                            R.string.blank_no_like_else));
                                    linBlank.setVisibility(View.VISIBLE);
                                    tvBlankNoLover.setVisibility(View.VISIBLE);
                                    tvBlankNoLove.setVisibility(View.VISIBLE);
                                }
                                likeRecommendListview.setNoData();

                            } else {
                                linBlank.setVisibility(View.GONE);
                                for (int i = 0; i < mlArticleLike.size(); i++) {
                                    boolean isRepeat = false;
                                    if (articleList.size() > 0) {
                                        for (int j = 0; j < articleList.size(); j++) {
                                            if (articleList.get(j).equals(mlArticleLike.get(i).getArticle())) {
                                                mlArticleLike.get(i).deleteInBackground();//删除重复的
                                                isRepeat = true;
                                                break;
                                            }
                                        }
                                    }
                                    if (!isRepeat) {//剔除重复
                                        articleList.add(mlArticleLike.get(i).getArticle());
                                    }
                                }
                                switch (what) {
                                    case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
                                        articleLikeList = articleList;
                                        likeRecommendListview.onRefreshComplete();
                                        // onLineListAdapter.setDatas(userList);
                                        break;
                                    case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
                                        likeRecommendListview.onLoadComplete();
                                        articleLikeList.addAll(articleList);
                                        break;
                                    case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
                                        articleLikeList = articleList;
                                        likeRecommendListview.onRefreshComplete();
                                        // onLineListAdapter.setDatas(userList);
                                        break;
                                }
                                likeRecommendListview
                                        .setResultSize(articleLikeList.size());
                                likeRecommendAdapter.setDatas(articleLikeList);
                                likeRecommendAdapter.notifyDataSetChanged();
                                isUpdateList = false; // 刷新完毕，设为false
                                // articleLikeList = articleList;
                                // likeRecommendAdapter.setDatas(articleLikeList);
                                // likeRecommendAdapter.notifyDataSetChanged();
                                // int listViewHeight = ViewUtil
                                // .setListViewHeightBasedOnChildren1(likeRecommendListview);
                            }
                        } else {
//                            Log.e("＝＝错误", "查询点赞错误: " + arg1.getMessage());
                            likeRecommendListview.setNoData();

                            if (articleLikeList.size() <= 0) {

                                linBlank.setVisibility(View.VISIBLE);
                                tvBlankNoLover.setVisibility(View.GONE);
                                tvBlankBg
                                        .setBackgroundResource(R.drawable.network_error);
                                tvBlankNoLove.setText(getResources().getString(
                                        R.string.blank_network_error));
                                linBlank.setOnClickListener(new OnClickListener() {

                                    @Override
                                    public void onClick(View arg0) {
                                        getUserLikerList(BEGIN_TO_LOADING);
                                    }
                                });
                            } else {
                                ToolKits.toast(getActivity(), "网络错误");
                            }
                        }
                    }
                });

            } else {
                // mLoadingDialog.dismiss();
                linBlank.setVisibility(View.VISIBLE);
                tvBlankNoLover.setVisibility(View.VISIBLE);
                // articleLikeList = null;
                // likeRecommendAdapter.setDatas(articleLikeList);
                // likeRecommendAdapter.notifyDataSetChanged();
            }
        } else {
            likeRecommendListview.setNoData();
            tvBlankBg.setBackgroundResource(R.drawable.blank_no_like);
            tvBlankNoLove.setText(getResources().getString(
                    R.string.blank_no_like));
            tvBlankNoLover.setText(getResources().getString(
                    R.string.blank_no_like_else));
            linBlank.setVisibility(View.VISIBLE);
            tvBlankNoLover.setVisibility(View.VISIBLE);
            tvBlankNoLove.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        // TODO Auto-generated method stub
        if (position - 1 < 0 || likeRecommendAdapter.getCount() <= 0) {
            return;
        }
        MLArticle selectArticle = (MLArticle) likeRecommendAdapter
                .getItem(position - 1);
        Intent intent = new Intent(getActivity(), TopicArticle.class);
        intent.putExtra("articleId", selectArticle.getObjectId());
        intent.putExtra("title", selectArticle.getTitle());
        intent.putExtra("intro", selectArticle.getIntro());
        intent.putExtra("likeCount",
                String.valueOf(selectArticle.getLikeCount()));
        intent.putExtra("shareCount",
                String.valueOf(selectArticle.getShareCount()));
        intent.putExtra("commentCount",
                String.valueOf(selectArticle.getCommentCount()));
        startActivity(intent);

    }

    @Override
    public void onLoad() {
        // TODO Auto-generated method stub
        getUserLikerList(AutoListView.LOAD);

    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        getUserLikerList(AutoListView.REFRESH);
        likeRecommendListview.setOnRefreshListener(this);
    }
}